import createFiber from "./fiber"
import { updateNode, isStr, Update } from "./utils"
import { renderHooks } from "./hooks"

export function updateHostComponent(wip) {
    if (!wip.stateNode) {
        wip.stateNode = createNode(wip)
    }
    // 协调子节点
    reconcileChildren(wip, wip.props?.children)
    // console.log('~~wip',wip)
}

export function updateFnComponent(wip) {
    // 重置当前节点的hooks相关公共变量
    renderHooks(wip)

    console.log('~~wip updateFnComponent', wip)
    const { type, props } = wip
    const children = type(props)
    console.log('~~children', children)
    reconcileChildren(wip, children)
}

function createNode(vnode) {
    const { type, props } = vnode
    const node = document.createElement(type)
    if (props) updateNode(node, {}, props)
    return node
}

// 遍历子节点，一个个创建成fiber，建立之间联系，并判断如果是更新则更改老fiber的相关属性
function reconcileChildren(wip, children) {
    if (isStr(children) || !children) return
    const newChildren = Array.isArray(children) ? children : [children]
    let oldFiber = wip.alterNate?.child
    let preNewFiber = null
    /*     newChildren.forEach(child => {
            const newFiber = createFiber(wip, child)
            if (newFiber && oldFiber) {
                const same = sameNode(oldFiber, newFiber)
                if (same) {
                    Object.assign(wip, {
                        alterNate: oldFiber,
                        stateNode: oldFiber.stateNode,
                        flags: Update
                    })
                }
                if (preNewFiber === null) { // 第一个child
                    wip.child = newFiber
                } else {
                    preNewFiber.sibling = newFiber
                }
                preNewFiber = newFiber
            }
    
        }); */
    for (let i = 0; i < newChildren.length; i++) {
        const child = newChildren[i]
        if (child === null) {
            continue
        }
        const newFiber = createFiber(wip, child)
        const same = sameNode(oldFiber, newFiber)
        if (same) {
            Object.assign(newFiber, {
                alterNate: oldFiber,
                stateNode: oldFiber.stateNode,
                flags: Update
            })
            console.log('~~wip 更新', wip)
        }
        if (oldFiber) {
            oldFiber = oldFiber.sibling
        }
        if (preNewFiber === null) { // 第一个child
            wip.child = newFiber
        } else {
            preNewFiber.sibling = newFiber
        }
        preNewFiber = newFiber

    }

}

function sameNode(a, b) {
    return !!(a && b && a.type === b.type && a.key === b.key)
}

